"""
AI场景数据库模型
"""

from datetime import datetime
from typing import List, Optional

from sqlalchemy import String, Text, Integer, DateTime, Enum, ForeignKey
from sqlalchemy.orm import relationship, Mapped, mapped_column
from sqlalchemy.sql import func

from config.database import Base
from .ai_web_scene import SceneStatus


class AIWebSceneModel(Base):
    """AI场景数据库模型"""
    __tablename__ = "ai_web_scene"

    # 主键和基本字段
    scene_id: Mapped[str] = mapped_column(String(50), primary_key=True, comment="场景唯一标识")
    scene_name: Mapped[str] = mapped_column(String(100), nullable=False, comment="场景名称")
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True, comment="场景描述")

    # 树形结构字段
    parent_id: Mapped[Optional[str]] = mapped_column(
        String(50),
        ForeignKey("ai_web_scene.scene_id", ondelete="SET NULL"),
        nullable=True,
        comment="父节点ID"
    )
    node_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True, comment="节点路径，格式：/父ID/子ID/...")
    node_level: Mapped[int] = mapped_column(Integer, default=0, comment="节点层级，根节点为0")
    sort_order: Mapped[int] = mapped_column(Integer, default=0, comment="同级节点排序序号")

    # 状态和元数据
    scene_status: Mapped[SceneStatus] = mapped_column(
        Enum(SceneStatus),
        default=SceneStatus.ACTIVE,
        comment="场景状态"
    )
    creator: Mapped[str] = mapped_column(String(50), nullable=False, comment="创建人")
    create_time: Mapped[datetime] = mapped_column(
        DateTime,
        default=func.now(),
        nullable=False,
        comment="创建时间"
    )
    modifier: Mapped[Optional[str]] = mapped_column(String(50), nullable=True, comment="修改人")
    modify_time: Mapped[Optional[datetime]] = mapped_column(
        DateTime,
        onupdate=func.now(),
        nullable=True,
        comment="修改时间"
    )
    version: Mapped[int] = mapped_column(Integer, default=0, comment="乐观锁版本号")

    # 关系定义
    children: Mapped[List["AIWebSceneModel"]] = relationship(
        "AIWebSceneModel",
        back_populates="parent",
        cascade="all, delete-orphan",
        order_by="AIWebSceneModel.sort_order"
    )
    parent: Mapped[Optional["AIWebSceneModel"]] = relationship(
        "AIWebSceneModel",
        back_populates="children",
        remote_side=[scene_id]
    )
    dialogs: Mapped[List["AIWebDialogModel"]] = relationship(
        "AIWebDialogModel",
        back_populates="scene",
        cascade="all, delete-orphan"
    )
    agents: Mapped[List["AIWebAgentModel"]] = relationship(
        "AIWebAgentModel",
        back_populates="scene",
        cascade="all, delete-orphan"
    )
    memories: Mapped[List["AIWebMemoryHisModel"]] = relationship(
        "AIWebMemoryHisModel",
        back_populates="scene",
        cascade="all, delete-orphan"
    )

    # 索引
    __table_args__ = (
        {"comment": "AI场景组合模式表"}
    )

    def __repr__(self):
        return f"<AIWebSceneModel(scene_id='{self.scene_id}', scene_name='{self.scene_name}', level={self.node_level})>"

    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "scene_id": self.scene_id,
            "scene_name": self.scene_name,
            "description": self.description,
            "parent_id": self.parent_id,
            "node_path": self.node_path,
            "node_level": self.node_level,
            "sort_order": self.sort_order,
            "scene_status": self.scene_status.value if self.scene_status else None,
            "creator": self.creator,
            "create_time": self.create_time.isoformat() if self.create_time else None,
            "modifier": self.modifier,
            "modify_time": self.modify_time.isoformat() if self.modify_time else None,
            "version": self.version
        }

    def is_root(self) -> bool:
        """判断是否为根节点"""
        return self.parent_id is None

    def is_leaf(self) -> bool:
        """判断是否为叶子节点"""
        return len(self.children) == 0

    def get_depth(self) -> int:
        """获取节点深度"""
        if self.is_leaf():
            return 0
        return max(child.get_depth() for child in self.children) + 1

    def get_all_descendants(self) -> List["AIWebSceneModel"]:
        """获取所有后代节点"""
        descendants = []
        for child in self.children:
            descendants.append(child)
            descendants.extend(child.get_all_descendants())
        return descendants

    def calculate_node_path(self) -> str:
        """计算节点路径"""
        if self.is_root():
            return "/"

        path_parts = []
        current = self.parent
        while current:
            path_parts.insert(0, current.scene_id)
            current = current.parent

        if path_parts:
            return "/" + "/".join(path_parts)
        return "/"

    def calculate_node_level(self) -> int:
        """计算节点层级"""
        level = 0
        current = self.parent
        while current:
            level += 1
            current = current.parent
        return level
